import { ideaTools, getQueryString } from "@gd-accbuild-core/config/utils";
import { globalConfig } from "@gd-accbuild-core/config";
let listenMsgCallback = null;
export default ({ bindInputVal, _store }) => {
  const inputVal = bindInputVal.value;
  const isInValidIframe = ideaTools.checkIsInValidIframe();
  if (isInValidIframe) {
    ideaTools.sendMsgToIDEA(({ parentUrl = "" }) => {
      const proxyUrl = getQueryString("proxyUrl").replace(/(.*)\/gd-sys/, "$1");
      const prefixUrl = getQueryString("baseStaticPrefixPath")
        ? getQueryString("baseStaticPrefixPath")
        : globalConfig["BASE_STATIC_PREFIX_PATH"];
      const url = `${proxyUrl}${prefixUrl}`;
      const allowRemoteLoadCompsUrl = `${url}/static/components/allowRemoteLoadComps.json?random=${
        Math.floor(Math.random() * (1 - 1000)) + 1000
      }`;
      return JSON.stringify({
        cmd: "designer:customizePick:init",
        data: {
          allowRemoteLoadCompsUrl,
          inputVal: inputVal
            ? JSON.parse(inputVal)
            : {
                componentFilePath: "",
                default: "",
                componentAttr: {},
              },
          projectRootPath: _store.state.designerEngine.curPickedProjectInfo.projectRootPath,
          spaceId: _store.state.designerEngine.curPickedProjectInfo.spaceId,
        },
      });
    });
    const loadingInstance = globalConfig.compService.loading({
      text: "自定义组件配置中请等待",
    });
    const cbListener = ({ data }) => {
      if (data.cmd === "designer:customizePick:res") {
        bindInputVal.value = data.data.data;
        globalConfig.compService.toast({
          message: "自定义组件上传成功",
          type: "success",
        });
      }
      loadingInstance.close();
      if (listenMsgCallback) {
        window.removeEventListener("message", listenMsgCallback, false);
      }
    };
    const o = ideaTools.receiveMsgFromIDEA(cbListener);
    listenMsgCallback = o.listenMsgCallback;
  } else {
    globalConfig.compService.toast({
      message: "请在HBuilderX中操作",
      type: "warning",
    });
  }
};

export const openSourceCodeFile = ({ bindInputVal, _store }) => {
  const inputVal = bindInputVal.value;
  const curInputVal = inputVal
    ? JSON.parse(inputVal)
    : {
        componentFilePath: "",
        default: "",
        componentAttr: {},
      };
  const isInValidIframe = ideaTools.checkIsInValidIframe();
  if (isInValidIframe && curInputVal.componentFilePath) {
    ideaTools.sendMsgToIDEA(({ parentUrl = "" }) => {
      return JSON.stringify({
        cmd: "designer:sourceCode:open",
        data: {
          filePath: `${_store.state.designerEngine.curPickedProjectInfo.projectRootPath}/src/static/components/customize/${curInputVal.componentFilePath}`,
          childPath: [],
        },
      });
    });
  }
};
